package com.rj2002.ctrl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/ue")
public class UeCtrl {
	
	public static final String UPLOAD_PATH = "F:/CPUV/filepc/";
	
	@ResponseBody
	@RequestMapping("/saveFile")
	public Map<String,Object> saveFile(@RequestParam(value="upfile",required = false)MultipartFile file,HttpSession session) throws IOException {
	    Map<String,Object> params = new HashMap<String, Object>();
//	    Img img = null;
//	    List<Img> imgs = null;
//	    if(session.getAttribute("imgs") != null) {
//	    	imgs = (List<Img>)session.getAttribute("imgs");
//	    	for (Img img2 : imgs) {
//	    		if(img2.getSize() == file.getSize()) {
//		    		params.put("state","SUCCESS");
//		    	    params.put("url",img2.getUrl());
//		    	    params.put("size",img2.getSize());
//		    	    params.put("original",file.getOriginalFilename());
//		    	    params.put("type",file.getContentType());
//		    	    return params;
//		    	}
//			}
//	    }else {
//			imgs = new ArrayList<Img>();
//		}
    	File filedir = new File(UPLOAD_PATH+"/ccc");
        if(!filedir.exists()) {
        	filedir.mkdirs();
        }
	    String path =  "F:/CPUV/filepc/ccc/" + getFileName(file);
	    File newFile = new File(path);
	    //通过CommonsMultipartFile的方法直接写文件
	    file.transferTo(newFile);
	    String visitUrl = "/user/down?path="+path;
	    params.put("state","SUCCESS");
	    params.put("url",visitUrl);
	    params.put("size",file.getSize());
	    params.put("original",file.getOriginalFilename());
	    params.put("type",file.getContentType());
//	    img = new Img(file.getSize(), visitUrl);
//	    imgs.add(img);
//	    session.setAttribute("imgs", imgs);
	    return params;
	}
	
	public static String getFileName(MultipartFile file) {
		//创建新文件的文件名
		//1.获取文件名后缀
		String extension = FilenameUtils.getExtension(file.getOriginalFilename()); 
		//2.生成随机的uuid作为文件名 并将原有的后缀拼接上去
		String newFileName = UUID.randomUUID().toString().replace("-", "") + "." + extension;
		return newFileName;
	}
	
	class Img{
		private Long size;
		private String url;
		
		public Img(Long size, String url) {
			super();
			this.size = size;
			this.url = url;
		}
		public Long getSize() {
			return size;
		}
		public void setSize(Long size) {
			this.size = size;
		}
		public String getUrl() {
			return url;
		}
		public void setUrl(String url) {
			this.url = url;
		}
	}
}